package edu.hit.pact.pgse.crawler.send;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;
import edu.hit.pact.pgse.bean.RunnableTask;
import edu.hit.pact.pgse.bean.TaskPiece;
import edu.hit.pact.pgse.communication.CommUtil;
import edu.hit.pact.pgse.communication.message.CrawlerDirRequestMessage;
import edu.hit.pact.pgse.crawler.CrawlerManager;
import edu.hit.pact.pgse.crawler.util.SleepThread;
import edu.hit.pact.pgse.crawler.web.WebTaskPiece;
import edu.hit.pact.pgse.util.Globals;

public class StoreNodeQuerier{
	private Log logger;
	private IoSession session;
	private StoreNodeQueryHandler pageQueryHandler;
	
	public StoreNodeQuerier() {
		this.logger = LogFactory.getLog(StoreNodeQuerier.class);
		SocketAddress dirAddress = new InetSocketAddress(Globals.DIRECTORY_ADDRESS_IP, Globals.DIRECTORY_ADDRESS_PORT);
		pageQueryHandler = new StoreNodeQueryHandler();
		CommUtil communicationUtil = new CommUtil(pageQueryHandler);
		session = communicationUtil.setConnector(dirAddress);
	}

	public InetSocketAddress getStore(TaskPiece piece) {
		logger.info("StoreNodeQuerier is running");
		CrawlerDirRequestMessage message = new CrawlerDirRequestMessage(piece.getHomePage());
		logger.info(message);
			
		if (session == null){
			logger.error("session is null");
			return null;
		}
		
		session.write(message);
		logger.info("message has been sent");

		while (!pageQueryHandler.isNewMessage())
			SleepThread.sleep(100); //wait for the reply message
			
		if (pageQueryHandler.isNewMessage()){
			InetSocketAddress storeAddr = pageQueryHandler.getStoreAddr();
			return storeAddr;
		} else {
			return null;
		}
	}
}
